package com.yupi.moonBI.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 消息过期机制
 */
public class TtlConsumer {

    public static final String QUEUE_NAME = "ttl_queue";

    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.88.130");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //创建队列，指定消息过期参数,过期时间10s
        Map<String,Object> arguments = new HashMap<String,Object>();
        arguments.put("x-message-ttl",10000);
        //args指定参数
        channel.queueDeclare(QUEUE_NAME,false,false,false,arguments);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        //定义了如何处理消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(message);
        };
        //消费消息，会持续阻塞
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });
    }
}
